package com.liucm.controller.publics;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.liucm.bean.State;
import com.liucm.bean.User;
import com.liucm.bean.Video;
import com.liucm.bean.VideoType;
import com.liucm.config.FilePathConfig;
import com.liucm.service.FocusService;
import com.liucm.service.RecordService;
import com.liucm.service.StateService;
import com.liucm.service.UserService;
import com.liucm.service.VideoService;
import com.liucm.service.VideoTypeService;
import com.liucm.util.MsgResponse;
import com.liucm.util.ThumbnailThread;
import sun.rmi.runtime.Log;

@Slf4j
@Controller
@RequestMapping("/VideoController")
public class VideoController {

    @Autowired
    private Video video;

    @Autowired
    private User user;

    @Autowired
    private VideoService videoService;

    @Autowired
    private VideoTypeService videoTypeService;

    @Autowired
    private UserService userService;

    @Autowired
    private FilePathConfig filePathConfig;

    @Autowired
    private StateService stateService;

    @Autowired
    private FocusService focusService;

    @Autowired
    private RecordService recordService;

    @RequestMapping("commented")
    @ResponseBody
    public MsgResponse commented(@RequestParam int starNum, @RequestParam int userId, @RequestParam int videoId) {
        return MsgResponse.success(videoService.addComment(starNum, userId, videoId), null);
    }

    @RequestMapping("VideoListByAjax")
    @ResponseBody
    public List<Video> getVideoListByAjax(HttpServletRequest request) {
        HttpSession session = request.getSession();
        int curPage = 0;
        if (session.getAttribute("curPage") != null) {
            curPage = Integer.parseInt(session.getAttribute("curPage").toString());
        }
        if (request.getParameter("curPage") != null) {
            curPage = Integer.parseInt(request.getParameter("curPage"));
        }
        curPage = curPage + 1;
        session.setAttribute("curPage", curPage);
        return videoService.getVideoListByAjax(curPage, 10);
    }

    @GetMapping("VideoListByTypeAjax")
    @ResponseBody
    public List<Video> getVideoListByTypeAjax(HttpServletRequest request, @RequestParam int videoTypeId) {
        return videoService.getVideoListByAjax(1, 8, videoTypeId);
    }

    @GetMapping("getVideoListByUserIdAjax")
    @ResponseBody
    public MsgResponse getVideoListByUserIdAjax(@RequestParam int userId) {
        List<Video> userVideo = videoService.getEnableVideoByUserId(userId);
        if (userVideo != null) {
            return MsgResponse.success("success", userVideo);
        }
        return MsgResponse.error("error");
    }

    @RequestMapping("getRecommendVideo")
    @ResponseBody
    public List<Video> getRecommendVideo(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");
        return videoService.getRecommendVideo(1, 6, user.getUserId());
    }

//	@RequestMapping("VideoTypeListByAjax")
//	@ResponseBody
//	public List<VideoType> getVideoTypeListByAjax(HttpServletRequest request) {
//		return videoTypeService.getVideoTypeAll();
//	}

    @RequestMapping("videoPlay")
    public ModelAndView videoPlay(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        String videoId = request.getParameter("videoId");
        Object obj = request.getSession().getAttribute("user");
        if (obj != null && videoId != null && !videoId.equals("")) {
            int videoId2 = Integer.parseInt(videoId);
            // 因为要观看要记录，故要增加观看次数
            String result = videoService.addViewSum(videoId2);
            Video video = videoService.getVideoByVideoId(videoId2);
            // 添加观看记录
            recordService.addRecord(((User) obj).getUserId(), videoId2);
            mv.addObject(result);
            if (video != null) {
                User user = userService.getUserByUserId(video.getUser().getUserId());
                video.setUser(user);
                VideoType videoType = videoTypeService.getVideoTypeByVideoTypeId(video.getVideoType().getVideoTypeId());
                video.setVideoType(videoType);
                request.getSession().setAttribute("curVideo", video);
            }
        }
        mv.setViewName("videoplay");
        return mv;
    }

	@RequestMapping("search")
	public ModelAndView searchVideoList(HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		String keyword = request.getParameter("keyword");
		Object obj = request.getSession().getAttribute("user");
		if (obj != null && keyword != null && !keyword.equals("")) {
			List<Video> videos = videoService.getVideoByKeyword(keyword);
			mv.addObject("searchlist",videos);
			int userId = ((User) obj).getUserId();
			User user = userService.getUserByUserId(userId);
			request.getSession().setAttribute("searchlist",videos);
			request.getSession().setAttribute("user", user);
		}
		mv.setViewName("search");
		return mv;
	}

    @PostMapping("getVideoByAjax")
    @ResponseBody
    public Video getVideoByAjax(@RequestParam String videoId) {

        return videoService.getVideoByVideoId(Integer.parseInt(videoId));
    }

    @GetMapping("enableVideoListByAjax")
    @ResponseBody
    public MsgResponse enableVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            return MsgResponse.success("获取上架视频成功", videoService.getEnableVideoByUserId(user.getUserId()));
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    @GetMapping("disableVideoListByAjax")
    @ResponseBody
    public MsgResponse disableVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            return MsgResponse.success("获取下架视频成功", videoService.getDisableVideoByUserId(user.getUserId()));
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    @GetMapping("verifyingVideoListByAjax")
    @ResponseBody
    public MsgResponse verifyingVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            return MsgResponse.success("获取正在视频成功", videoService.getVerifyingVideoByUserId(user.getUserId()));
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    @GetMapping("verifiedVideoListByAjax")
    @ResponseBody
    public MsgResponse verifiedVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            return MsgResponse.success("获取已认证视频成功", videoService.getVerifiedVideoByUserId(user.getUserId()));
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    @GetMapping("verifyFalseVideoListByAjax")
    @ResponseBody
    public MsgResponse verifyFalseVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            return MsgResponse.success("获取认证失败视频成功", videoService.getVerifyFalseVideoByUserId(user.getUserId()));
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    @GetMapping("focusedVideoListByAjax")
    @ResponseBody
    public MsgResponse focusedVideoListByAjax(HttpServletRequest request) {
        User user = request.getSession().getAttribute("user") != null ? (User) request.getSession().getAttribute("user")
                : null;
        if (user != null) {
            List<Integer> fdList = focusService.getUserFocusList(user.getUserId());
            List<Video> videoList = new ArrayList<Video>();
            for (Integer userId : fdList) {
                videoList.addAll(videoService.getEnableVideoByUserId(userId));
            }
            Collections.sort(videoList);
            return MsgResponse.success("获取认证失败视频成功", videoList);
        } else {
            return MsgResponse.error("当前用户不存在");
        }
    }

    /**
     * 首页推荐视频
     *
     * @return
     */
    @RequestMapping("videoRecommend")
    @ResponseBody
    public List<Video> videoRecommend() {
        List<Video> recommend = videoService.getVideoRecommend(10);
        return recommend;
    }

    /**
     * @param videoId
     * @return
     */
    @RequestMapping("upStoreByAjax")
    @ResponseBody
    public String upStoreByAjax(@RequestParam String videoId) {
        videoService.upStore(Integer.parseInt(videoId));
        return "true";
    }

    @RequestMapping("downStoreByAjax")
    @ResponseBody
    public String downStoreByAjax(@RequestParam String videoId) {
        if (videoService.downStore(Integer.parseInt(videoId)) == 1) {
            return "true";
        } else {
            return "true";
        }
    }

    @PostMapping("reVerifyVideo")
    @ResponseBody
    public boolean reVerifyVideo(@RequestParam int videoId) {
        return videoService.verifyVideo(videoId, 1);

    }

    /**
     * 发送Ajax请求删除视频
     *
     * @param videoId
     * @return
     */
    @RequestMapping("deleteVideoByAjax")
    @ResponseBody
    public String deleteVideoByAjax(@RequestParam String videoId) {
        if (videoService.deleteVideo(Integer.parseInt(videoId)).equals("true")) {
            return "true";
        } else {
            return "true";
        }
    }

    /**
     * 发送Ajax请求点赞
     *
     * @param request
     * @param videoId
     * @return
     */
    @RequestMapping("DianZanByAjax")
    @ResponseBody
    public MsgResponse DianZanByAjax(HttpServletRequest request, @RequestParam String videoId) {
        user = (User) request.getSession().getAttribute("user");
        String msg = videoService.addVideoDianZanSum(user, Integer.parseInt(videoId));
        if (msg.equals("点赞成功")) {
            return MsgResponse.success(msg, null);
        } else {
            return MsgResponse.error(msg);
        }
    }

    /**
     * 发送Ajax请求修改视频信息
     *
     * @param videoId
     * @param videoTitle
     * @param videoInfo
     * @param videoTypeId
     * @return
     */
    @RequestMapping("updateVideoByAjax")
    @ResponseBody
    public String updateVideoByAjax(@RequestParam String videoId, @RequestParam String videoTitle,
                                    @RequestParam String videoInfo, @RequestParam String videoTypeId) {
        Video video = videoService.getVideoByVideoId(Integer.parseInt(videoId));
        video.setVideoTitle(videoTitle);
        video.setVideoInfo(videoInfo);
        VideoType videoType = new VideoType();
        videoType.setVideoTypeId(Integer.parseInt(videoTypeId));
        video.setVideoType(videoType);
        try {
            videoService.updateVideo(video);
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

    }

    /**
     * 上传视频
     *
     * @param videoFile
     * @param videoTitle
     * @param videoInfo
     * @param typeName
     * @param userId
     * @return
     */
    @PostMapping("videoUpload")
    @ResponseBody
    public MsgResponse videoUpload(@RequestParam("videoFile") MultipartFile videoFile, @RequestParam("image") MultipartFile image, @RequestParam String videoTitle,
                                   @RequestParam String videoInfo, @RequestParam String typeName, @RequestParam String userId) {


        log.info("进入上传视频接口，开始上传视频...");

        if (videoFile != null && !videoFile.isEmpty()) {
            if (!videoFile.getOriginalFilename().contains(".")) {
                return MsgResponse.error("文件格式错误！");
            }

            //保存视频文件

            //下面一个是文件名，一个是视频文件保存地址
            // 视频的保存路劲
            // 数据库中保存的:文件名=时间戳.后缀,路径=path+文件名（）
            String saveFileName = filePathConfig.getVideoPath() + System.currentTimeMillis()
                    + videoFile.getOriginalFilename().substring(videoFile.getOriginalFilename().lastIndexOf('.'));
            String FileRealPath = filePathConfig.getFileUrl() + saveFileName;// 保存的到本地的URL

            log.info("saveFileName =" + FileRealPath);

            File dest = new File(FileRealPath);

            log.info("判断文件父目录是否存在。。");
            if (!dest.getParentFile().exists()) {
                // 判断文件父目录是否存在
                dest.getParentFile().mkdirs();
            }

            log.info("保存视频文件。。");
            // 保存文件
            try {
                videoFile.transferTo(dest);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("视频文件保存完成。。");

            //保存视频封面

            //下面一个是文件名，另一个是视频封面保存地址
            // 视频的保存路劲
            // 数据库中保存的:文件名=时间戳.后缀,路径=path+文件名（）
            String imageName = System.currentTimeMillis()
                    + image.getOriginalFilename().substring(image.getOriginalFilename().lastIndexOf('.'));
            String saveImageName = filePathConfig.getImagePath() + imageName;
            String imageRealPath = filePathConfig.getFileUrl() + saveImageName;// 保存的到本地的URL
            log.info("saveFileName =" + imageRealPath);

            File destImage = new File(imageRealPath);

            log.info("判断图片的父目录是否存在。。");
            if (!destImage.getParentFile().exists()) {
                // 判断文件父目录是否存在
                destImage.getParentFile().mkdirs();
            }

            log.info("保存视频封面。。");
            // 保存文件
            try {
                image.transferTo(destImage);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            log.info("视频封面保存完成");

            //部署的时候，这个需要进行修改
            String url = "http://10.106.15.189.223:80/VideoController/downloadImage?path=" + imageName;

            log.info("视频封面的地址："+url);

            int userIdInt = 0;

            if (userId != null && !userId.equals("")) {

                // 将上传视频的用户的用户ID:userId设置为int类型
                userIdInt = Integer.parseInt(userId);

                // 截图的保存路劲
                // imagePath=\\images\\
                //String thumbnailUrl = filePathConfig.getImagePath() + System.currentTimeMillis() + ".jpg";
                //String thumbnailRealPath = filePathConfig.getFileUrl() + thumbnailUrl;

                //视频截图
                //ThumbnailThread thumbnailThread = new ThumbnailThread(FileRealPath, thumbnailRealPath);
                //thumbnailThread.start();

                video.setUser(userService.getUserByUserId(userIdInt));
                video.setVideoTitle(videoTitle);
                video.setVideoInfo(videoInfo);
                video.setVideoUrl(saveFileName);
                //video.setThumbnailUrl(thumbnailUrl);
                video.setThumbnailUrl(url);
                video.setVideoType(videoTypeService.getVideoTypeByTypeName(typeName));
                State state = stateService.getStateByStateId(1);
                video.setVideoState(state);
                videoService.addVideo(video);
            }

        } else {
            return MsgResponse.error("上传失败:文件不存在");
        }
        return MsgResponse.success("上传成功", null);
    }


    //下载图片
    @RequestMapping("/downloadImage")
    public void downloadModel(String path, HttpServletRequest request, HttpServletResponse response) {
        //http://localhost:80/VideoController/downloadImage?path=1638372198353.jpg
        String filePath = filePathConfig.getFileUrl() + filePathConfig.getImagePath() + path;
        System.out.println(path);

        response.setContentType("charset=UTF-8");
        response.addHeader("Content-Disposition", "inline;filename=" + filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("----文件不存在----" + filePath);
        }

        InputStream fis = null;
        OutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        System.out.println("----开始传输文件----");
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            fos = response.getOutputStream();
            bos = new BufferedOutputStream(fos);
            int bytesRead = 0;
            byte[] bytes = new byte[1024];
            while ((bytesRead = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, bytesRead);
            }
            bos.flush();
            System.out.println("----文件传输成功----");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                bis.close();
                fos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //下载图片
    @RequestMapping("/downloadVideo")
    public void downloadVideo(String path, HttpServletRequest request, HttpServletResponse response) {
        //http://localhost:80/VideoController/downloadImage?path=1638372198353.jpg
        String filePath = filePathConfig.getFileUrl() + filePathConfig.getVideoPath()+ path;
        System.out.println(path);

        response.setContentType("charset=UTF-8");
        response.addHeader("Content-Disposition", "inline;filename=" + filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            System.out.println("----文件不存在----" + filePath);
        }

        InputStream fis = null;
        OutputStream fos = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        System.out.println("----开始传输文件----");
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            fos = response.getOutputStream();
            bos = new BufferedOutputStream(fos);
            int bytesRead = 0;
            byte[] bytes = new byte[1024];
            while ((bytesRead = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, bytesRead);
            }
            bos.flush();
            System.out.println("----文件传输成功----");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
                bis.close();
                fos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
